#include "HTTP.h"
#include "../StringOps/StringOps.h"
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>

void HTTPRequest::fill(std::string url) {
	// Split URL into parts
	struct URL parts = generate_url(url);

	// Resolve host name
	struct addrinfo hints, *res;
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = PF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags |= AI_CANONNAME;
	int result = getaddrinfo(parts.host_name.c_str(), NULL, &hints, &res);
	// Do error checking

	freeaddrinfo(res);

	// Get address information
	struct sockaddr_in host;
	host.sin_family = AF_INET;
	host.sin_port = htons(80);
	memcpy(&host.sin_addr.s_addr, res->ai_addr->sa_data+2, 4);
	//printf("IP: %s\n", inet_ntoa(host.sin_addr));

	// Connect to host
	int sock = socket(AF_INET, SOCK_STREAM, 0);
	result = connect(sock, (struct sockaddr*)&host, sizeof(host));
	// do error checking
	//printf("result of connect: %d\n", result);

	// Send HTTP request
	//printf("Before send\n");
	std::string request = "GET " + parts.path + " HTTP/1.1\r\n";
	request = request + "Host: " + parts.host_name + "\r\n\r\n";
	printf("%s",request.c_str());
	result = send(sock, request.c_str(), request.size(), 0);
	//printf("After send\n");
	// do error checking

	// Get response
	std::string response;
	char c;
	//printf("Before receive\n");
	while((result = recv(sock, &c, 1, 0)) == 1)
		response.push_back(c);
	//printf("After receive\n");
	// do error checking

	// Parse response
	//printf("Got here!\n");
	//printf("%s\n", response.c_str());
	error_code = get_error_code(response);
	//printf("1\n");
	error_description = get_error_description(response);
	//printf("2\n");
	date = get_date(response);
	//printf("3\n");
	expires = get_expires(response);
	//printf("4\n");
	body = get_body(response);
	//printf("5\n");
}
